package com.letianpai.activity.photoalbum;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;

import com.letianpai.R;
import com.letianpai.adapter.photoalbum.PagerAdapter;
import com.letianpai.gesture.ScaleGestureDetector;
import com.letianpai.view.ImageViewTouch;
import com.letianpai.view.ViewPager;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * Created by Administrator on 2014/10/15.
 */
public class BrowsePhotoActivity extends Activity implements OnClickListener {

	private static final String TAG = BrowsePhotoActivity.class.getSimpleName();

	private static final int PAGER_MARGIN_DP = 40;

	private ViewPager mViewPager;
	private ImagePagerAdapter mPagerAdapter;
	private ScaleGestureDetector mScaleGestureDetector;
	private boolean mPaused;
	private boolean mOnScale = false;
	private boolean mOnPagerScoll = false;
	private ImageLoader imageLoader;
	private DisplayImageOptions options; // 配置图片加载及显示选项

	// 传入参数
	private List<String> mImageList;
	private int mPosition;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.browse_photo);
		ImageButton backTv = (ImageButton) findViewById(R.id.top_back_ib);
		backTv.setOnClickListener(new BackOnClickListener());
		mViewPager = (ViewPager) findViewById(R.id.viewPager);
		final float scale = getResources().getDisplayMetrics().density;
		int pagerMarginPixels = (int) (PAGER_MARGIN_DP * scale + 0.5f);
		mViewPager.setPageMargin(pagerMarginPixels);
		mViewPager.setPageMarginDrawable(new ColorDrawable(Color.BLACK));

		mPagerAdapter = new ImagePagerAdapter();
		mViewPager.setAdapter(mPagerAdapter);
		setupOnTouchListeners(mViewPager);

		options = new DisplayImageOptions.Builder()
		// .showStubImage(R.drawable.ic_launcher) // 在ImageView加载过程中显示图片
				.showImageForEmptyUri(R.drawable.ic_launcher) // image连接地址为空时
				.showImageOnFail(R.drawable.add_home) // image加载失败
				.cacheInMemory(true) // 加载图片时会在内存中加载缓存
				.cacheOnDisc(true) // 加载图片时会在磁盘中加载缓存
				.displayer(new RoundedBitmapDisplayer(5, false)) // 设置用户加载图片task(这里是圆角图片显示)
				.build();
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration
				.createDefault(BrowsePhotoActivity.this));
		Intent mIntent = getIntent();
		// 参数传入
		mImageList = mIntent.getStringArrayListExtra("PHOTO_INFO_LIST");
		mPosition = mIntent.getIntExtra("CURRENT_POSITION", 0);

		mViewPager.setCurrentItem(mPosition, false);
	}

	@Override
	public void onStart() {
		super.onStart();
		mPaused = false;
	}

	@Override
	public void onStop() {
		super.onStop();
		mPaused = true;
	}

	private void setupOnTouchListeners(View rootView) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
			mScaleGestureDetector = new ScaleGestureDetector(this,
					new MyOnScaleGestureListener());
		}

		OnTouchListener rootListener = new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
					if (!mOnPagerScoll) {
						mScaleGestureDetector.onTouchEvent(event);
					}
				}

				ImageViewTouch imageView = getCurrentImageView();
				if (imageView == null) {
					return true;
				}
				if (!mOnScale) {
					Matrix m = imageView.getImageViewMatrix();
					RectF rect = new RectF(0, 0, imageView.mBitmapDisplayed
							.getBitmap().getWidth(), imageView.mBitmapDisplayed
							.getBitmap().getHeight());
					m.mapRect(rect);
					// 图片超出屏幕范围后移动
					if (!(rect.right > imageView.getWidth() + 0.1 && rect.left < -0.1)) {
						try {
							mViewPager.onTouchEvent(event);
						} catch (ArrayIndexOutOfBoundsException e) {
							// why?
						}
					}
				}
				return true;
			}
		};

		rootView.setOnTouchListener(rootListener);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent m) {
		if (mPaused)
			return true;
		return super.dispatchTouchEvent(m);
	}

	@Override
	protected void onDestroy() {
		ImageViewTouch imageView = getCurrentImageView();
		if (imageView != null) {
			imageView.mBitmapDisplayed.recycle();
			imageView.clear();
		}
		super.onDestroy();
	}

	private ImageViewTouch getCurrentImageView() {
		return (ImageViewTouch) mPagerAdapter.views.get((mViewPager
				.getCurrentItem()));
	}

	private class MyOnScaleGestureListener extends
			ScaleGestureDetector.SimpleOnScaleGestureListener {

		float currentScale;
		float currentMiddleX;
		float currentMiddleY;

		@Override
		public void onScaleEnd(ScaleGestureDetector detector) {
			final ImageViewTouch imageView = getCurrentImageView();
			if (imageView == null) {
				return;
			}

			Log.d(TAG, "currentScale: " + currentScale + ", maxZoom: "
					+ imageView.mMaxZoom);
			if (currentScale > imageView.mMaxZoom) {
				// imageView
				// .zoomToNoCenterWithAni(currentScale
				// / imageView.mMaxZoom, 1, currentMiddleX,
				// currentMiddleY);
				// currentScale = imageView.mMaxZoom;
				// imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
				// currentMiddleY);
			} else if (currentScale < imageView.mMinZoom) {
				// imageView.zoomToNoCenterWithAni(currentScale,
				// imageView.mMinZoom, currentMiddleX, currentMiddleY);
				// currentScale = imageView.mMinZoom;
				// imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
				// currentMiddleY);
			} else {
				imageView.zoomToNoCenter(currentScale, currentMiddleX,
						currentMiddleY);
			}

			imageView.center(true, true);

			// NOTE: 延迟修正缩放后可能移动问题
			imageView.postDelayed(new Runnable() {
				@Override
				public void run() {
					mOnScale = false;
				}
			}, 300);
			Log.d(TAG, "gesture onScaleEnd");
		}

		@Override
		public boolean onScaleBegin(ScaleGestureDetector detector) {
			// Log.d(TAG, "gesture onScaleStart");
			mOnScale = true;
			return true;
		}

		@Override
		public boolean onScale(ScaleGestureDetector detector, float mx, float my) {
			// Log.d(TAG, "gesture onScale");
			ImageViewTouch imageView = getCurrentImageView();
			if (imageView == null) {
				return true;
			}
			float ns = imageView.getScale() * detector.getScaleFactor();
			currentScale = ns;
			currentMiddleX = mx;
			currentMiddleY = my;
			if (detector.isInProgress()) {
				imageView.zoomToNoCenter(ns, mx, my);
			}
			return true;
		}
	}

	private class ImagePagerAdapter extends PagerAdapter {
		public Map<Integer, ImageViewTouch> views = new HashMap<Integer, ImageViewTouch>();

		@Override
		public int getCount() {
			// Log.d(TAG, "getCount");
			return mImageList.size();
		}

		@Override
		public Object instantiateItem(View container, int position) {
			// Log.d(TAG, "instantiateItem");
			ImageViewTouch imageView = new ImageViewTouch(
					BrowsePhotoActivity.this);
			imageView.setLayoutParams(new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			imageView.setBackgroundColor(Color.BLACK);
			imageView.setFocusableInTouchMode(true);

			imageLoader.displayImage(mImageList.get(position), imageView,
					options, null);
			((ViewPager) container).addView(imageView);
			views.put(position, imageView);
			return imageView;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			// Log.d(TAG, "destroyItem");
			ImageViewTouch imageView = (ImageViewTouch) object;
			imageView.mBitmapDisplayed.recycle();
			imageView.clear();
			((ViewPager) container).removeView(imageView);
			views.remove(position);
		}

		@Override
		public void startUpdate(View container) {
			// Log.d(TAG, "startUpdate");
		}

		@Override
		public void finishUpdate(View container) {
			// Log.d(TAG, "finishUpdate");
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			// Log.d(TAG, "isViewFromObject");
			return view == ((ImageViewTouch) object);
		}

		@Override
		public Parcelable saveState() {
			// Log.d(TAG, "saveState");
			return null;
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
			// Log.d(TAG, "restoreState");
		}
	}

	@Override
	public void onClick(View v) {

	}

	class BackOnClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			returnBack();
		}
	}

	private void returnBack() {
		Intent intent = new Intent();
		intent.setAction("com.letianpai.album.action.broadcast");
		sendBroadcast(intent);
		finish();
	}

}
